package com.jiangjiang.eshop.logistics.calculator;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jiangjiang.eshop.logistics.dto.FreightTemplateDTO;
import com.jiangjiang.eshop.order.dto.OrderInfoDTO;
import com.jiangjiang.eshop.order.dto.OrderItemDTO;
import org.springframework.stereotype.Component;

/**
 * @ClassName CustomRuleFreightCalculator
 * @Description 自定义运费计算规则
 * @Author jhw
 * @Date 2021/9/20 22:28
 * @Version 1.0
 **/
@Component
public class CustomRuleFreightCalculator implements FreightCalculator{
    /**
     * 计算订单条目运费
     * @param freightTemplate 运费模板
     * @param order 订单数据
     * @param orderItem 订单条目
     * @return
     */
    @Override
    public Double calculate(FreightTemplateDTO freightTemplate, OrderInfoDTO order, OrderItemDTO orderItem) {
        String province = getProvinceFromAddress(order.getDeliveryAddress());
        Double totalGrossWeight = orderItem.getGoodsGrossWeight() * orderItem.getPurchaseQuantity();


        JSONArray rules = JSONArray.parseArray(freightTemplate.getRule());
        for (int i = 0; i < rules.size(); i++) {
            JSONObject rule = rules.getJSONObject(i);
            String provinces = rule.getString("provinces");
            if(!provinces.contains(province)){
                continue;
            }
            Double threshold = rule.getDoubleValue("threshold");
            Double thresholdFreight = rule.getDoubleValue("threshold_freight");
            Double incrStep = rule.getDoubleValue("incr_step");
            Double incrFreight = rule.getDoubleValue("incr_freight");

            if(totalGrossWeight <= threshold){
                return thresholdFreight;
            } else {
                return thresholdFreight + (totalGrossWeight - threshold) / incrStep * incrFreight;
            }
        }


        return 0.0;
    }


    /**
     * 从地址中提取省份
     * @param address 地址
     * @return 处理结果
     */
    private String getProvinceFromAddress(String address){
        return address.substring(0, address.indexOf("省"));
    }
}
